const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🏗️ 开始初始化施工队伍数据')
  console.log('📊 云函数环境信息:', {
    env: cloud.DYNAMIC_CURRENT_ENV,
    requestId: context.requestId,
    event: event
  })

  try {
    // 施工队伍模拟数据
    const constructionTeams = [
      {
        id: 'team_001',
        name: '张师傅电气工程',
        type: 'individual',
        auditStatus:'approved',
        typeName: '个人师傅',
        category: 'electrical',
        categoryName: '电气工程',
        avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200',
        experience: '15年',
        rating: 4.9,
        completedProjects: 156,
        location: '贵州省贵阳市',
        phone: '138****8888',
        specialties: ['强电安装', '弱电布线', '配电箱安装', '故障维修'],
        certifications: ['电工证', '高级电工证', '安全作业证'],
        description: '从事电气工程15年，经验丰富，技术过硬，服务态度好，价格合理。',
        priceRange: '200-500元/天',
        status: 'available',
        joinDate: '2023-03-15',
        tags: ['经验丰富', '技术过硬', '服务好评'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_002',
        name: '华建装饰工程有限公司',
        auditStatus:'approved',
        type: 'company',
        typeName: '施工公司',
        category: 'decoration',
        categoryName: '装修装饰',
        avatar: 'https://images.unsplash.com/photo-1560472354-b33ff0c44a43?w=200',
        experience: '8年',
        rating: 4.8,
        completedProjects: 89,
        location: '贵州省遵义市',
        phone: '400-123-4567',
        specialties: ['室内装修', '办公装修', '商业装修', '精装修'],
        certifications: ['建筑装修装饰工程专业承包资质', 'ISO9001认证', '安全生产许可证'],
        description: '专业装修装饰公司，拥有专业设计团队和施工队伍，承接各类装修工程。',
        priceRange: '面议',
        status: 'available',
        joinDate: '2022-08-20',
        tags: ['专业团队', '设计施工一体', '质量保证'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_003',
        name: '李师傅水暖维修',
        auditStatus:'approved',
        type: 'individual',
        typeName: '个人师傅',
        category: 'plumbing',
        categoryName: '水暖工程',
        avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200',
        experience: '12年',
        rating: 4.7,
        completedProjects: 203,
        location: '贵州省六盘水市',
        phone: '139****9999',
        specialties: ['管道安装', '卫浴安装', '暖气维修', '防水工程'],
        certifications: ['管道工证', '防水工证'],
        description: '专业水暖师傅，技术娴熟，24小时上门服务，解决各种水暖问题。',
        priceRange: '150-400元/天',
        status: 'busy',
        joinDate: '2023-01-10',
        tags: ['24小时服务', '技术娴熟', '快速响应'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_004',
        name: '智联网络工程公司',
        auditStatus:'approved',
        type: 'company',
        typeName: '施工公司',
        category: 'network',
        categoryName: '网络工程',
        avatar: 'https://images.unsplash.com/photo-1551434678-e076c223a692?w=200',
        experience: '10年',
        rating: 4.9,
        completedProjects: 67,
        location: '贵州省安顺市',
        phone: '400-567-8901',
        specialties: ['网络布线', '机房建设', '监控安装', '智能化系统'],
        certifications: ['信息系统集成资质', '安防工程资质', '弱电工程资质'],
        description: '专业网络工程公司，提供网络规划、设计、施工、维护一站式服务。',
        priceRange: '面议',
        status: 'available',
        joinDate: '2022-11-05',
        tags: ['一站式服务', '专业资质', '技术领先'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_005',
        name: '王师傅暖通空调',
        auditStatus:'approved',
        type: 'individual',
        typeName: '个人师傅',
        category: 'hvac',
        categoryName: '暖通空调',
        avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=200',
        experience: '18年',
        rating: 4.8,
        completedProjects: 134,
        location: '贵州省毕节市',
        phone: '137****7777',
        specialties: ['中央空调安装', '地暖安装', '新风系统', '设备维修'],
        certifications: ['制冷工证', '暖通工程师证'],
        description: '暖通空调专业师傅，经验丰富，提供安装、维修、保养全方位服务。',
        priceRange: '300-600元/天',
        status: 'available',
        joinDate: '2023-05-22',
        tags: ['经验丰富', '全方位服务', '技术专业'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_006',
        name: '安盾安防科技公司',
        auditStatus:'approved',
        type: 'company',
        typeName: '施工公司',
        category: 'security',
        categoryName: '安防监控',
        avatar: 'https://images.unsplash.com/photo-1560472354-b33ff0c44a43?w=200',
        experience: '6年',
        rating: 4.6,
        completedProjects: 45,
        location: '贵州省铜仁市',
        phone: '400-789-0123',
        specialties: ['监控系统', '门禁系统', '报警系统', '智能安防'],
        certifications: ['安防工程企业资质', '安全技术防范系统设计施工维修资格证'],
        description: '专业安防公司，提供监控、门禁、报警等安防系统的设计安装服务。',
        priceRange: '面议',
        status: 'available',
        joinDate: '2023-07-18',
        tags: ['专业安防', '系统集成', '售后保障'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_007',
        auditStatus:'approved',
        name: '黔南建筑工程队',
        type: 'company',
        typeName: '施工公司',
        category: 'decoration',
        categoryName: '装修装饰',
        avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=200',
        experience: '12年',
        rating: 4.7,
        completedProjects: 78,
        location: '贵州省黔南州',
        phone: '400-456-7890',
        specialties: ['民族特色装修', '古建筑修复', '现代装饰', '园林景观'],
        certifications: ['建筑装饰工程专业承包资质', '古建筑工程专业承包资质'],
        description: '专注于贵州民族特色装修和古建筑修复，融合现代设计理念。',
        priceRange: '面议',
        status: 'available',
        joinDate: '2022-12-10',
        tags: ['民族特色', '古建修复', '文化传承'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_008',
        auditStatus:'approved',
        name: '陈师傅电气维修',
        type: 'individual',
        typeName: '个人师傅',
        category: 'electrical',
        categoryName: '电气工程',
        avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=200',
        experience: '20年',
        rating: 4.9,
        completedProjects: 245,
        location: '贵州省黔东南州',
        phone: '135****6666',
        specialties: ['工业电气', '民用电气', '应急抢修', '节能改造'],
        certifications: ['高级电工证', '特种作业操作证', '电气工程师证'],
        description: '从事电气工程20年，经验丰富，擅长各类电气故障排除和系统优化。',
        priceRange: '250-550元/天',
        status: 'available',
        joinDate: '2023-02-28',
        tags: ['经验丰富', '技术全面', '应急响应'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        id: 'team_009',
        auditStatus:'approved',
        name: '黔西南水利工程公司',
        type: 'company',
        typeName: '施工公司',
        category: 'plumbing',
        categoryName: '水暖工程',
        avatar: 'https://images.unsplash.com/photo-1560472354-b33ff0c44a43?w=200',
        experience: '15年',
        rating: 4.8,
        completedProjects: 56,
        location: '贵州省黔西南州',
        phone: '400-678-9012',
        specialties: ['水利工程', '给排水系统', '污水处理', '农村饮水'],
        certifications: ['水利水电工程施工总承包资质', '环保工程专业承包资质'],
        description: '专业水利工程公司，致力于贵州山区水利基础设施建设。',
        priceRange: '面议',
        status: 'busy',
        joinDate: '2022-05-15',
        tags: ['水利专业', '山区经验', '环保工程'],
        createTime: new Date(),
        updateTime: new Date()
      }
    ]

    console.log('📦 准备插入数据，总数:', constructionTeams.length)

    // 测试数据库连接
    console.log('🔗 测试数据库连接...')
    try {
      const testResult = await db.collection('construction_teams').limit(1).get()
      console.log('✅ 数据库连接成功，当前数据条数:', testResult.data.length)
    } catch (connectError) {
      console.error('❌ 数据库连接失败:', connectError)
      throw new Error(`数据库连接失败: ${connectError.message}`)
    }

    // 清空现有数据
    console.log('🗑️ 开始清空现有数据...')
    try {
      const removeResult = await db.collection('construction_teams').where({}).remove()
      console.log('✅ 清空现有施工队伍数据，删除条数:', removeResult.stats.removed)
    } catch (removeError) {
      console.error('⚠️ 清空数据时出错:', removeError)
      // 继续执行，不因清空失败而终止
    }

    // 改进的插入方式：分批插入以避免超时
    const batchSize = 3 // 每批插入3条数据
    const results = []
    const errors = []

    for (let i = 0; i < constructionTeams.length; i += batchSize) {
      const batch = constructionTeams.slice(i, i + batchSize)
      console.log(`📦 处理第 ${Math.floor(i/batchSize) + 1} 批数据，包含 ${batch.length} 条记录`)

      for (const team of batch) {
        try {
          console.log(`   正在插入: ${team.name} (${team.typeName})`)
          
          const result = await db.collection('construction_teams').add({
            data: team
          })
          
          results.push({
            id: team.id,
            name: team.name,
            insertId: result._id,
            success: true
          })
          
          console.log(`   ✅ 插入成功: ${team.name}`)
          
        } catch (insertError) {
          console.error(`   ❌ 插入失败: ${team.name}`, insertError)
          errors.push({
            id: team.id,
            name: team.name,
            error: insertError.message,
            success: false
          })
        }
      }

      // 每批之间稍作延迟，避免并发问题
      if (i + batchSize < constructionTeams.length) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }

    // 验证插入结果
    console.log('🔍 验证插入结果...')
    try {
      const verifyResult = await db.collection('construction_teams').get()
      console.log('✅ 验证完成，数据库中实际数据条数:', verifyResult.data.length)
      
      const finalResult = {
        success: true,
        message: '施工队伍数据初始化成功',
        data: {
          totalCount: constructionTeams.length,
          successCount: results.length,
          errorCount: errors.length,
          actualDbCount: verifyResult.data.length,
          results: results,
          errors: errors.length > 0 ? errors : undefined,
          summary: `成功插入 ${results.length}/${constructionTeams.length} 条数据`
        }
      }

      console.log('🎉 施工队伍数据初始化完成')
      console.log('📊 最终结果:', finalResult.data.summary)
      
      return finalResult

    } catch (verifyError) {
      console.error('❌ 验证插入结果失败:', verifyError)
      
      return {
        success: results.length > 0, // 如果有成功插入的数据，仍然算部分成功
        message: results.length > 0 ? '部分数据初始化成功，但验证失败' : '数据初始化失败',
        data: {
          totalCount: constructionTeams.length,
          successCount: results.length,
          errorCount: errors.length,
          results: results,
          errors: errors,
          verifyError: verifyError.message
        }
      }
    }

  } catch (error) {
    console.error('❌ 施工队伍数据初始化失败:', error)
    console.error('❌ 错误堆栈:', error.stack)
    
    return {
      success: false,
      error: error.message,
      details: {
        errorType: error.constructor.name,
        errorStack: error.stack,
        timestamp: new Date().toISOString()
      }
    }
  }
}
